package com.xiaotao.controller;


import com.alibaba.fastjson.JSONObject;
import com.xiaotao.bo.RequestMessage;
import com.xiaotao.util.ResponseEnum;
import com.xiaotao.util.ResponseUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/chatai")
public class CustomerServiceController {
    @Resource
    private RestTemplate restTemplate;
    @PostMapping("/message2")
    public ResponseUtil receiveMessage2 (@RequestBody RequestMessage requestMessage) {
//       请求体数据
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("message",  requestMessage.getMessage());
        requestBody.put("mode", "chat");
        requestBody.put("userId", requestMessage.getUserId());
//  请求头数据
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        requestHeaders.set("Authorization","Bearer 8W5H6C0-1JS4E8E-HGEPBWW-93T963S");  // AIkey
        requestHeaders.set("accept", "application/json");
        HttpEntity<Map<String, Object>> r = new HttpEntity<Map<String, Object>>(requestBody, requestHeaders);

        String url = "http://localhost:3001/api/v1/workspace/workspace/thread/494a16ff-c493-48df-a6fa-c432e3c281b4/chat";
        String content = restTemplate.postForObject(url, r, String.class);
        JSONObject jsonObject = JSONObject.parseObject(content);
        String aiAnswer = (String)jsonObject.get("textResponse");
        String[] splitResult = aiAnswer.split("\\$\\$"); // 必须用双反斜杠转义 $
        if (splitResult.length >= 2) {
            content = splitResult[1]; // 取分割后的第二部分（AI回复内容）
        } else {
            content = aiAnswer; // 分割失败使用原始内容
        }
//        content = aiAnswer.split("</think>")[1];
        return  ResponseUtil.get(ResponseEnum.OK,content);
    }
}
